﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

namespace OrganizedIN.UI.GroupContact
{
    public partial class SearchUser : System.Web.UI.Page
    {
        OIDataContext dc = new OIDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    if (Request["action"] != null && Request["uid"] != null)
                    {
                        var fc = (from d in dc.Contacts
                                  where d.FromUName == Session["UserID"].ToString() && d.ToUName == Request["uid"]
                                  select d).SingleOrDefault();
                        var tc = (from d in dc.Contacts
                                  where d.FromUName == Request["uid"] && d.ToUName == Session["UserID"].ToString()
                                  select d).SingleOrDefault();
                        dc.Contacts.DeleteOnSubmit(fc);
                        dc.Contacts.DeleteOnSubmit(tc);
                        dc.SubmitChanges();
                        Response.Redirect("Contacts.aspx", false);
                    }
                    BindExistingContacts();
                }
                catch (Exception ex) { }
            }
        }

        private void BindExistingContacts()
        {
            string uname = Session["UserID"].ToString();
            var result = (from d in dc.Contacts
                          where d.FromUName == uname && d.Approved == true
                          select new { Name = d.UserInformation1.FirstName + " " + d.UserInformation1.LastName, UserName = d.UserInformation1.username, ProfilePicture = (d.UserInformation1.ProfilePicture == null || d.UserInformation1.ProfilePicture == "") ? "~/images/user-icon.jpg" : d.UserInformation1.ProfilePicture }).Distinct().AsEnumerable();
            rptrExistingUsers.DataSource = result;
            rptrExistingUsers.DataBind();
        }

        protected void btnAdd_Click(object sender, ImageClickEventArgs e)
        {
            string uname = Session["UserID"].ToString();
            ImageButton ib = (ImageButton)sender;
            if (ib.CommandName == "select")
            {
                var data = (from d in dc.Contacts
                            where d.FromUName == uname && d.ToUName == ib.CommandArgument
                            select d).SingleOrDefault();
                if (data == null)
                {
                    Contact fc = new Contact();
                    fc.FromUName = uname;
                    fc.ToUName = ib.CommandArgument;
                    fc.Approved = true;
                    fc.Rejected = false;
                    fc.RequestDate = DateTime.Now;
                    fc.RejectionCount = 0;
                    Contact tc = new Contact();
                    tc.FromUName = ib.CommandArgument;
                    tc.ToUName = uname;
                    tc.Approved = false;
                    tc.Rejected = false;
                    tc.RequestDate = null;
                    tc.RejectionCount = 0;
                    dc.Contacts.InsertOnSubmit(fc);
                    dc.Contacts.InsertOnSubmit(tc);
                    dc.SubmitChanges();
                    lblError.ForeColor = Color.Green;
                    lblError.Text = "Your request was successfully sent !";
                }
                else
                {
                    if (data.RejectionCount >= 3 && data.RequestDate != null)
                    {
                        lblError.ForeColor = Color.Red;
                        lblError.Text = "Your request was rejected 3 times so cannot send request again !";
                    }
                    else
                    {
                        Contact fc = (from d in dc.Contacts
                                      where d.FromUName == uname && d.ToUName == ib.CommandArgument
                                      select d).SingleOrDefault();
                        Contact tc = (from d in dc.Contacts
                                      where d.FromUName == ib.CommandArgument && d.ToUName == uname
                                      select d).SingleOrDefault();
                        if (tc.Approved == false && tc.Rejected == true)
                        {
                            fc.RequestDate = DateTime.Now;
                            tc.RequestDate = null;
                            tc.Rejected = false;
                        }
                        else
                        {
                            fc.FrndshpDate = DateTime.Now;
                            tc.FrndshpDate = DateTime.Now;
                            fc.RejectionCount = 0;
                            tc.RejectionCount = 0;
                        }
                        fc.Approved = true;
                        fc.Rejected = false;
                        dc.SubmitChanges();
                        lblError.ForeColor = Color.Green;
                        lblError.Text = "Your request was successfully sent !";
                    }
                }
                BindRepeater();
                BindExistingContacts();
            }
            else if (ib.CommandName == "view")
            {
                Response.Redirect("../Profile/MyProfile.aspx?uid=" + ib.CommandArgument, false);
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindRepeater();
        }

        private void BindRepeater()
        {
            string tag = txtSearch.Text;
            string uname = Session["UserID"].ToString();
            var data = (from d in dc.UserInformations
                        where (d.FirstName.ToLower().IndexOf(tag) != -1 || d.LastName.ToLower().IndexOf(tag) != -1 || d.username.ToLower().IndexOf(tag) != -1) && d.username != Session["UserID"].ToString()
                        select new { Name = d.FirstName + " " + d.LastName, d.Gender, d.DOB, d.username, ProfilePicture = (d.ProfilePicture == null || d.ProfilePicture == "") ? "~/images/user-icon.jpg" : d.ProfilePicture, IsFriend = d.Contacts1.Where(a => a.FromUName == uname && a.Approved == true).Count() == 0 ? false : true });
            rptrUsers.DataSource = data;
            rptrUsers.DataBind();
        }

        protected void gvRequests_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string uname = Session["UserID"].ToString();
            if (e.CommandName == "confirm")
            {
                Contact tc = (from d in dc.Contacts
                              where d.Contact_ID == Convert.ToInt64(e.CommandArgument.ToString())
                              select d).SingleOrDefault();
                Contact fc = (from d in dc.Contacts
                              where d.FromUName == tc.ToUName && d.ToUName == uname
                              select d).SingleOrDefault();

                fc.FrndshpDate = DateTime.Now;
                tc.FrndshpDate = DateTime.Now;
                fc.RejectionCount = 0;
                tc.RejectionCount = 0;
                tc.Approved = true;
                tc.Rejected = false;
                dc.SubmitChanges();
                gvRequests.DataBind();
                BindExistingContacts();
            }
            else if (e.CommandName == "reject")
            {
                Contact tc = (from d in dc.Contacts
                              where d.Contact_ID == Convert.ToInt64(e.CommandArgument.ToString())
                              select d).SingleOrDefault();
                Contact fc = (from d in dc.Contacts
                              where d.FromUName == tc.ToUName && d.ToUName == uname
                              select d).SingleOrDefault();

                fc.RejectionCount += 1;
                tc.RejectionCount += 1;
                tc.Approved = false;
                tc.Rejected = true;
                fc.Approved = false;
                fc.Rejected = true;
                dc.SubmitChanges();
                gvRequests.DataBind();
                BindExistingContacts();
            }
        }
    }
}